<template>
  <div class="product-list">
    <!-- 搜索和分类 -->
    <div class="filter-bar">
      <div class="search">
        <input type="text" placeholder="搜索产品..." v-model="searchKeyword" />
        <button @click="search">搜索</button>
      </div>
      <div class="categories">
        <button 
          v-for="category in categories" 
          :key="category" 
          :class="{ active: currentCategory === category }"
          @click="filterByCategory(category)"
        >
          {{ category }}
        </button>
      </div>
    </div>

   
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else class="products-grid">
      <div class="product-card" v-for="product in filteredProducts" :key="product.id">
        <img :src="product.image" :alt="product.name" class="product-image" @click="goToProductDetail(product.id)" />
        <div class="product-info">
          <div class="product-category">{{ product.category }}</div>
          <h3 class="product-name" @click="goToProductDetail(product.id)">{{ product.name }}</h3>
          <p class="product-desc">{{ product.desc }}</p>
          <div class="product-price">¥{{ product.price }}</div>
          <div class="product-rating">
            <span v-for="i in 5" :key="i" class="star" :class="{ filled: i <= product.rating }">★</span>
            ({{ product.rating }})
          </div>
          <div class="product-actions">
            <button class="add-to-cart-btn" @click="addToCart(product)">
              加入购物车
            </button>
            <button class="buy-now-btn" @click="buyNow(product)">
              立即购买
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '../stores/cart'
import { productAPI } from '../services/api'

const router = useRouter()
const cartStore = useCartStore()

// 状态管理
const products = ref([])
const categories = ref([])
const searchKeyword = ref('')
const currentCategory = ref('全部')
const loading = ref(false)

// 加载产品和分类数据
const loadProducts = async (params = {}) => {
  loading.value = true
  try {
    const response = await productAPI.getProducts(params)
    products.value = response.data.products.map(product => ({
      id: product.id,
      name: product.name,
      category: product.category?.name || '未分类',
      price: product.price,
      desc: product.shortDescription || product.description || '产品描述',
      image: product.images?.[0] || 'https://picsum.photos/300/200?random=1',
      rating: 4.5 // 后端暂无评分字段，使用默认值
    }))
  } catch (error) {
    console.error('加载产品失败:', error)
    // 备用数据
    products.value = [
      {
        id: 1,
        name: '智能手机',
        category: '电子产品',
        price: 2999,
        desc: '最新款智能手机，拥有强大的性能和优秀的拍照功能',
        image: 'https://picsum.photos/300/200?random=1',
        rating: 4.8
      },
      {
        id: 2,
        name: '无线耳机',
        category: '电子产品',
        price: 599,
        desc: '高品质无线蓝牙耳机，音质清晰，佩戴舒适',
        image: 'https://picsum.photos/300/200?random=2',
        rating: 4.6
      }
    ]
  } finally {
    loading.value = false
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await productAPI.getCategories()
    categories.value = ['全部', ...response.data.categories.map(cat => cat.name)]
  } catch (error) {
    console.error('加载分类失败:', error)
    categories.value = ['全部', '电子产品', '服装', '家居', '运动', '书籍']
  }
}

// 筛选产品
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    // 分类筛选
    const categoryMatch = currentCategory.value === '全部' || product.category === currentCategory.value
    // 搜索筛选
    const searchMatch = product.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) || 
                       product.desc.toLowerCase().includes(searchKeyword.value.toLowerCase())
    return categoryMatch && searchMatch
  })
})

// 分类筛选方法
const filterByCategory = (category) => {
  currentCategory.value = category
  if (category !== '全部') {
    loadProducts({ category: category })
  } else {
    loadProducts()
  }
}

// 搜索方法
const search = () => {
  if (searchKeyword.value.trim()) {
    loadProducts({ search: searchKeyword.value })
  } else {
    loadProducts()
  }
}

// 跳转到产品详情
const goToProductDetail = (id) => {
  router.push({ name: 'ProductDetail', params: { id } })
}

// 加入购物车
const addToCart = (product) => {
  cartStore.addToCart(product)
  alert('已添加到购物车！')
}

// 立即购买
const buyNow = (product) => {
  cartStore.clearCart()
  cartStore.addToCart(product)
  router.push({ name: 'Orders' })
}

onMounted(() => {
  loadProducts()
  loadCategories()
})
</script>

<style scoped>
.product-list {
  padding: 20px;
}
.filter-bar {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}
.search {
  display: flex;
  gap: 8px;
}
.search input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.search button {
  padding: 8px 16px;
  background: #6a4a9e;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.categories {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.categories button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}
.categories button.active {
  background: #6a4a9e;
  color: white;
  border-color: #6a4a9e;
}
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}
.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}
.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}
.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.product-info {
  padding: 16px;
}
.product-category {
  font-size: 12px;
  color: #6a4a9e;
  margin-bottom: 8px;
}
.product-name {
  font-size: 18px;
  margin-bottom: 8px;
}
.product-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.product-price {
  font-size: 20px;
  font-weight: bold;
  color: #e64340;
  margin-bottom: 8px;
}
.product-rating {
  font-size: 14px;
  color: #ffc107;
  margin-bottom: 12px;
}
.star.filled {
  color: #ffc107;
}

.product-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.add-to-cart-btn, .buy-now-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.add-to-cart-btn {
  background: #3498db;
  color: white;
}

.add-to-cart-btn:hover {
  background: #2980b9;
}

.buy-now-btn {
  background: #e74c3c;
  color: white;
}

.buy-now-btn:hover {
  background: #c0392b;
}
</style>